package com.spider.common.web.controller;


import com.spider.common.utils.NumberUtil;
import com.spider.common.utils.ServletUtils;
import com.spider.common.utils.StringUtils;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 基类action
 * @version 1.0
 * @author marver
 * @created 2018年9月30日
 */
@Controller
@Scope("prototype")
public abstract class BaseController {

	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){  
        this.request = request;  
        this.response = response;  
        this.session = request.getSession();  
    }  

	/**
	 * 设置一个Token 。 放置重复提交<br/>
	 * 转向页面的时候根据指定的tokenName名字 在session中存储一个值字符的"true",提交页面时在处理接受的方法中调用
	 * isTonten方法判断session中的值
	 * 
	 * @param tokenName
	 *            指定的Token名称
	 * @param request
	 */
	protected void setToken(String tokenName, HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		session.setAttribute(tokenName, "true");
	}

	/**
	 * 判断session中Token的值<br/>
	 * 根据指定的tokenName获取session中对应的值，如果该值符合条件则改变session中的值并返会"" <br/>
	 * 如果不符合条件则返回 提示信息
	 * 
	 * @param tokenName
	 *            request
	 * @param request
	 * @return 符合条件返回true， 否则返回false
	 */
	protected String isToken(String tokenName, HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		String tokenValue = (String) session.getAttribute(tokenName);
		String paramValue = (String) request.getParameter(tokenName);

		// 参数、session中都没用token值提示错误
		if (StringUtil.isBlank(paramValue) && StringUtil.isBlank(tokenValue)) {
			return "会话Token未设定！";
		} else if (StringUtil.isBlank(paramValue)
				&& !StringUtil.isBlank(tokenValue)) {
			return "表单Token未设定！";
		} else if (paramValue.equals(tokenValue)
				&& !StringUtil.isBlank(tokenValue) && "true".equals(tokenValue)) { // session中有token,防止重复提交检查
			session.setAttribute(tokenName, "false");
			return "";
		} else {
			return "请勿重复提交！";
		}
	}


	protected Integer paramInt(HttpServletRequest request, String str) {
		return NumberUtil.getInteger(request.getParameter(str));
	}

	protected Long paramLong(HttpServletRequest request, String str) {
		return NumberUtil.getLong(request.getParameter(str));
	}

	protected String paramString(HttpServletRequest request, String str) {
		return StringUtils.isNull(request.getParameter(str));
	}

	protected String success(ModelMap model) {
		return "success";
	}

	protected String error(ModelMap model) {
		return "error";
	}
	
	//@ExceptionHandler({Exception.class})
	public void exceptionHandler(Exception e, HttpServletResponse response) {
		 Map<String, Object> res = new HashMap<String, Object>();
		res.put("code", "400");
		res.put("msg", "系统出错了，请检查参数是否正确");
		logger.error("Exception:", e);
		ServletUtils.writeToResponse(response, res);
	}
	
	
	/*@ExceptionHandler({MethodArgumentNotValidException.class})
	public void notNullException(MethodArgumentNotValidException e, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<String, Object>();
		res.put("code", "400");
		BindingResult bindingResult = e.getBindingResult();
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			res.put("msg", msg);
		} else {
			res.put("msg", e.getMessage());
		}
		logger.error("MethodArgumentNotValidException:", e);
		ServletUtils.writeToResponse(response, res);
	}*/

    //@ExceptionHandler({RuntimeException.class})
    public void runtimeExcptionDispose(RuntimeException e, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("code", 500);
        res.put("msg", "系统出错了");

		logger.error("RuntimeException", e);

        ServletUtils.writeToResponse(response, res);
    }
    
    /*@ExceptionHandler({BindException.class})
    public void bindException(BindException e, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("code", 500);
        res.put("msg", "数据保存失败，请稍后重试");
    
		logger.error("参数校验失败"+ e.getFieldError().getDefaultMessage(), e);

        ServletUtils.writeToResponse(response, res);
    }*/


	public Map<String, Object> getRequestFormMap(HttpServletRequest request) throws UnsupportedEncodingException{
        String str = getRequestParams(request);
		Map<String, Object> params = new HashMap<String, Object>();
		Enumeration<String> paramNames = request.getParameterNames();  
        while (paramNames.hasMoreElements()) {  
            String paramName = (String) paramNames.nextElement();  
  
            String[] paramValues = request.getParameterValues(paramName);  
            if (paramValues.length == 1) {  
                String paramValue = paramValues[0];  
                if (paramValue.length() != 0) {  
                	params.put(paramName, paramValue);  
                }  
            }  
        }  
		if(StringUtils.isNotBlank(str) && params.size()==0){
			String str1 = java.net.URLDecoder.decode(str, "UTF-8");
			String[] strs = str.split("name=");
			String[] strs1 = str1.split("&");
			for (int i = 1; i < strs.length; i++) {
				String temp = strs[i].substring(0, strs[i].indexOf("------"));
				int index = temp.indexOf("\"", 1);
				index = index + 1;
				String key = temp.substring(0, index);
				String value = temp.substring(index, temp.length());
				params.put(key, value);
			}
			for (int i = 0; i < strs1.length; i++) {
				String[] temp = strs1[i].split("=");
				params.put(temp[0], temp[1]);
			}
		}
        return params;
    }
    
	/**
	 * 使用 request.getInputStream()读取回调数据流
	 * 
	 * @param request
	 * @return
	 */
	public String getRequestParams(HttpServletRequest request) {
		String params = "";
		try {
			request.setCharacterEncoding("UTF-8");
			InputStream in = request.getInputStream();
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			params = sb.toString();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return params;
	}
}
